package cn.site.modules.sys.utils;

import java.util.Map;

import cn.site.core.service.BaseService;
import cn.site.core.utils.SpringContextHolder;
import cn.site.modules.sys.dao.UserDao;
import cn.site.modules.sys.entity.User;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;

import com.google.common.collect.Maps;

import cn.site.modules.sys.security.SystemAuthorizingRealm.Principal;

/**
 * 用户工具类
 * <p/>
 * Created by ZGJ on 2015/3/8.
 */
public class UserUtils extends BaseService {

    private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);

    public static final String CACHE_USER = "user";

    public static User getUser() {
        //缓存中是否存有user对象
        User user = (User) getCache(CACHE_USER);
        if (user == null) {
            try {
                Subject subject = SecurityUtils.getSubject();
                Principal principal = (Principal) subject.getPrincipal();
                if (principal != null) {
                    user = userDao.findOne(principal.getId());
                    putCache(CACHE_USER, user);
                }
            } catch (Exception e) {

            }
        }
        if (user == null) {
            user = new User();
            try {
                SecurityUtils.getSubject().logout();
            } catch (Exception e) {

            }
        }
        return user;
    }


    /*public static List<Role> getRoleList(){
        @SuppressWarnings("unchecked")
        List<Role> list = (List<Role>)getCache(CACHE_ROLE_LIST);
        if (list == null){
            User user = getUser();
            DetachedCriteria dc = roleDao.createDetachedCriteria();
            dc.createAlias("userList", "userList", JoinType.LEFT_OUTER_JOIN);
            dc.add(Restrictions.eq(Role.FIELD_DEL_FLAG, Role.DEL_FLAG_NORMAL));
            dc.addOrder(Order.asc("name"));
            list = roleDao.find(dc);
            putCache(CACHE_ROLE_LIST, list);
        }
        return list;
    }*/

    /*public static List<Menu> getMenuList(){
        @SuppressWarnings("unchecked")
        List<Menu> menuList = (List<Menu>) getCache(CACHE_MENU_LIST);
        if (menuList == null) {
            User user = getUser();
            if (user.isAdmin()) {
                menuList = menuDao.findAllList();
            } else {
                menuList = menuDao.findByUserId(user.getId());
            }
            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }*/

    /*public static List<Area> getAreaList(){
        @SuppressWarnings("unchecked")
        List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST);
        if (areaList == null){
            areaList = areaDao.findAllList();
            putCache(CACHE_AREA_LIST, areaList);
        }
        return areaList;
    }*/

    public static User getUser(String id) {
        if (StringUtils.isNotBlank(id)) {
            return userDao.findOne(id);
        } else {
            return null;
        }
    }

    public static User getUser(boolean isRefresh) {
        if (isRefresh) {
            removeCache(CACHE_USER);
        }
        return getUser();
    }

    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
        Object obj = getCacheMap().get(key);
        return ((obj == null) ? defaultValue : obj);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String, Object> getCacheMap() {
        Map map = Maps.newHashMap();
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();
            return ((principal != null) ? principal.getCacheMap() : map);
        } catch (UnavailableSecurityManagerException e) {

        } catch (InvalidSessionException e) {

        }
        return map;
    }

    public static void putCache(String key, Object value) {
        getCacheMap().put(key, value);
    }

    public static void removeCache(String key) {
        getCacheMap().remove(key);
    }

}
